package Leetcode;

/**
 * @Author piper
 * @Date 2019/10/21 10:20 上午
 */
public class 力扣35_搜索插入位置 {

    /**
     * 从前往后依次比较
     * 碰到大于或者等于的返回位置
     * 如果碰不到这样的数据 返回数组长度
     */
    static int searchInsert(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] >= target) {
                return i;
            }
        }
        return nums.length;
    }

    /**
     * 二分查找方式
     */
    static int searchInsert2(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }


    public static void main(String[] args) {
        System.out.println(searchInsert(new int[]{1, 3, 5, 6}, 0));
        System.out.println(searchInsert(new int[]{1, 3, 5, 6}, 1));
        System.out.println(searchInsert(new int[]{1, 3, 5, 6}, 6));
        System.out.println(searchInsert(new int[]{1, 3, 5, 6}, 7));
    }
}
